<template>
  <view class="high-light" :class="className">
    <template v-if="keyword.length == 0">{{ text }}</template>
    <template v-else>
      <template v-for="(item, index) in filterList">
        <text v-if="item.deep" class="light" :key="index">{{ item.val }}</text>
        <template v-else>{{ item.val }}</template>
      </template>
    </template>
  </view>
</template>

<script>
export default {
  props: {
    text: String,
    keyword: {
      type: String,
      default: "",
    },
    className: String,
  },
  data() {
    return {
      filterList: [],
    };
  },
  watch: {
    keyword: {
      handler(newVal) {
        if (newVal.length > 0) {
          this.filterHighlight(this.text, newVal);
        }
      },
      immediate: true,
    },
  },
  methods: {
    // 非空过滤
    changeText(e) {
      this.filterHighlight(this.text, e);
    },
    /**
     * 关键字高亮处理
     * @param { String } text - 文本
     * @param { String } key - 关键字
     */
    filterHighlight(text, key) {
      let textList = text.split("");
      let keyList = key.split("");
      let list = [];
      for (let i = 0; i < textList.length; i++) {
        let obj = {
          deep: false,
          val: textList[i],
        };
        list.push(obj);
      }
      for (let k = 0; k < keyList.length; k++) {
        list.forEach((item) => {
          if (
            item.val === keyList[k] ||
            item.val.toLowerCase() === keyList[k].toLowerCase()
          ) {
            item.deep = true;
          }
        });
      }
      this.filterList = list;
    },
  },
};
</script>

<style lang="scss" scoped>
.high-light {
  // display: inline-block;
  width: 100%;
  .light {
    color: $high-light;
  }
}
</style>
